<?php

namespace app\index\controller;

use addons\tools\model\UserVip;
use app\common\controller\Frontend;
use app\common\model\User;
use think\Db;
use think\Log;
use Yansongda\Pay\Pay;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        $user = new \app\common\service\queue\User();
        $user->update_free_meal_handle();

        return $this->view->fetch();
    }

    public function notify()
    {
        Pay::config(config('pay'));
//        $data = Pay::wechat()->callback();
//        if (!$data) Log::error('验签失败！');
        $data['resource'] = [
            'ciphertext' => [
                'out_trade_no'   => '2023122110052545',
                'transaction_id' => time(),
                'amount'         => [
                    'payer_total' => 1
                ]
            ]
        ];
        try {
            Db::transaction(function () use ($data) {
                $out_trade_no = $data['resource']['ciphertext']['out_trade_no'];
                $transaction_id = $data['resource']['ciphertext']['transaction_id'];
                $w = ['order_sn' => $out_trade_no, 'pay_status' => 0];
                if ($order = \addons\tools\model\MealOrder::where($w)->find()) {
                    //1.更新订单
                    $order->isUpdate(true)->save([
                        'pay_status' => 1,
                        'trade_no'   => $transaction_id,
                        'pay_time'   => time(),
                        'pay_price'  => bcdiv($data['resource']['ciphertext']['amount']['payer_total'], 100, 2)
                    ]);
                    $user = (new User())->where('status', 'normal')->find($order->user_id);
                    if ($user) {
                        //2.更新日期
                        $userVip = new  UserVip();
                        $userVip->where('user_id', $order->user_id)->update([
                            'update_vip' => 1,
                            'attach'     => json_encode(['meal_id' => $order->meal_id])
                        ]);
//                        $this->updateMemberTime((int)$order->user_id, $order->days, $number);
                        //3.添加记录
//                        $logData = [
//                            'user_id' => $order->user_id,
//                            'before'  => $user->tools_use_num,
//                            'after'   => $user->tools_use_num + $number,
//                            'memo'    => '购买会员新增次数'
//                        ];
//                        $this->createNumberLog($logData);
                    }

                }
            });
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
        }
        return Pay::wechat()->success();
    }

}
